<?php

namespace App\Http\Controllers;

use App\Models\Contact\Contact as ContactModel;
use App\Models\Contact\Type as TypeModel;
use App\Models\Region as RegionModel;
use App\Models\User\User as UserModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Validator;

class ContactController extends Controller
{
    // 添加联系人
    public function add()
    {
        // 查询省份
        $province = RegionModel::where(['grade' => 1])->select('code','name')->get();

        // 查询分类
        $TypeList = TypeModel::get();

        $data = compact([
            'province',
            'TypeList'
        ]);

        return view('home.contact.add',$data);
    }

    public function edit()
    {
        $contactid = request('contactid');

        $Contact = ContactModel::find($contactid);

        if(!$Contact)
        {
            return redirect()->route('error',['msg' => '该联系人不存在，请重新选择','url' => url('/')]);
        }

        if($Contact['region'])
        {
            $parentpath = RegionModel::where(['code' => $Contact['region']])->value('parentpath');

            [$province,$city,$district] = explode(',',$parentpath);

            if($province)
            {
                $Contact['province'] = $province;
            }

            if($city)
            {
                $Contact['city'] = $city;
            }

            if($district)
            {
                $Contact['district'] = $district;
            }
        }

        // 查询省份
        $provinces = RegionModel::where(['grade' => 1])->select('code','name')->get();

        // 查询分类
        $TypeList = TypeModel::get();

        // 查询市
        if(isset($Contact['province']))
        {
            $citys = RegionModel::where(['parentid' => $Contact['province']])->select('code','name')->get();
        }else{
            $citys = [];
        }

        // 查询区
        if(isset($Contact['city']))
        {
            $districts = RegionModel::where(['parentid' => $Contact['city']])->select('code','name')->get();
        }else{
            $districts = [];
        }

        $data = compact([
            'provinces',
            'citys',
            'districts',
            'TypeList',
            'Contact'
        ]);

        return view('home.contact.edit',$data);
    }

    public function editform(Request $request)
    {
        $LoginUser = !empty($request->cookie('LoginUser')) ? json_decode($request->cookie('LoginUser'),true) : [];

        $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;

        $User = UserModel::find($userid);

        if(!$User)
        {
            Cookie::queue(Cookie::forget('LoginUser'));
            return redirect()->route('error',['msg' => '非法登录','url' => url('home/user/login')]);
        }

        $contactid = request('contactid');

        $Contact = ContactModel::find($contactid);

        if(!$Contact)
        {
            return redirect()->route('error',['msg' => '该联系人不存在，请重新选择','url' => url('/')]);
        }

        // 接收全部参数
        $params = $request->all();

        $ContactList = ContactModel::where('id','<>',$contactid)->get();

        // 判断输入的手机号是否存在
        foreach ($ContactList as $item) {
            if($item->phone == $params['phone'])
            {
                return redirect()->route('error',['msg' => '该手机号已存在，请重新输入']);
            }
        }

        $parentpath = RegionModel::where(['code' => $params['district']])->value('parentpath');

        if(!$parentpath)
        {
            return redirect()->route('error',['msg' => '所选地区不存在']);
        }

        // 封装更新数据
        $data = [
            'nickname' => $params['nickname'],
            'phone' => $params['phone'],
            'gender' => $params['gender'],
            'region' => $params['district'],
            'remark' => $params['remark'],
            'typeid' => $params['typeid'],
        ];

        $result = ContactModel::where('id',$contactid)->update($data);

        if($result === FALSE)
        {
            return redirect()->route('error',['msg' => '更新失败']);
        }else{
            return redirect()->route('success',['msg' => '更新成功','url' => url('/')]);
        }
    }

    public function addform(Request $request)
    {
        $LoginUser = !empty($request->cookie('LoginUser')) ? json_decode($request->cookie('LoginUser'),true) : [];

        $userid = !empty($LoginUser['id']) ? $LoginUser['id'] : 0;

        $User = UserModel::find($userid);

        if(!$User)
        {
            Cookie::queue(Cookie::forget('LoginUser'));
            return redirect()->route('error',['msg' => '非法登录','url' => url('home/user/login')]);
        }

        $params = $request->all();

        $params['userid'] = $userid;

        // 验证规则
        $rules = [
            'nickname' => 'required',
            'phone' => 'required|unique:contact',
            'typeid' => 'required',
            'remark' => 'required',
            'userid' => 'required',
        ];

        // 错误信息
        $message = [
            'nickname.required' => '昵称必填',
            'phone.required' => '手机号必填',
            'phone.unique' => '该手机已存在，请重新输入',
            'typeid.required' => '分类id未知',
            'remark.required' => '备注必填',
            'userid.required' => '用户id未知',
        ];

        $validator = Validator::make($params,$rules,$message);

        if($validator->fails())
        {
            return redirect('home/contact/add')->withErrors($validator)->withInput();
        }

        $parentpath = RegionModel::where(['code' => $params['district']])->value('parentpath');

        if(!$parentpath)
        {
            return redirect()->route('error',['msg' => '所选地区不存在']);
        }

        $data = [
            'nickname' => $params['nickname'],
            'phone' => $params['phone'],
            'gender' => $params['gender'],
            'region' => $params['district'],
            'remark' => $params['remark'],
            'typeid' => $params['typeid'],
            'userid' => $params['userid'],
        ];

        $result = ContactModel::create($data);

        if($result === FALSE)
        {
            return redirect()->route('error',['msg' => '新增失败']);
        }else{
            return redirect()->route('success',['msg' => '新增成功','url' => url('/')]);
        }
    }

    public function del()
    {
        $id = request('id');

        $Contact = ContactModel::find($id);

        $result = $Contact->delete();

        if($result === FALSE)
        {
            return json_encode(['code' => 0,'msg' => '删除失败']);
        }else{
            return json_encode(['code' => 1,'msg' => '删除成功']);
        }
    }
}
